package com.example.controller;

import com.baomidou.mybatisplus.core.batch.MybatisBatch;
import com.example.entity.Account;
import com.example.mapper.AccountMapper;
import com.example.service.AccountService;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 单表
 * 不使用 sharding jdbc
 */
@RestController
@RequestMapping("/account")
public class AccountController {

    @Resource
    private AccountService accountService;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private DataSource dataSource;


    @GetMapping("/list")
    public List<Account> listAll() {
        try {
            Connection connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return accountService.list();
    }

    @GetMapping("/get")
    public Account getAccount(@RequestParam("id") Integer id) {
        return accountMapper.getAccountById(id);
    }

    /**
     * // todo
     * 1，指定表不受 sharding jdbc 影响
     * 2，save batch 原理
     * 3，批量插入时 唯一键忽略
     */
    @GetMapping("/batch_insert")
    public String batchInsert() {
        List<Account> accountList = new ArrayList<>();
//        for (int i = 0; i < 50; i++) {
//            accountList.add(new Account("test" + i, 100 + i, 10000L + i, "test" + i));
//        }
        accountList.add(new Account("test1", 102, 100001L, "test1"));
        accountList.add(new Account("test2", 102, 100001L, "test1"));

        boolean b = accountService.saveBatch(accountList);

        return b ? "success" : "false";
    }


    @GetMapping("/batch_ignore_insert")
    public Integer batchIgnoreInsert() {
        List<Account> accountList = new ArrayList<>();
        accountList.add(new Account("test1", 102, 100001L, "test1"));
        accountList.add(new Account("test2", 102, 100001L, "test1"));

        return accountMapper.insertIgnoreIntoList(accountList);
    }

    @GetMapping("/test_spring_event")
    public String testSpringEvent() {
        accountService.testSpringEvent();
        return "success";
    }

}
